package com.wangnian.wangcai.service.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangnian.wangcai.config.Config;
import com.wangnian.wangcai.dao.ChiGu;
import com.wangnian.wangcai.dao.NameInfo;
import com.wangnian.wangcai.dao.NameInfoDao;
import com.wangnian.wangcai.util.CommonUtil;
import com.wangnian.wangcai.util.HttpUtil;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class QmtService implements ApiService {

    private static final Logger logger = LoggerFactory.getLogger(QmtService.class);

    @Autowired
    private NameInfoDao nameInfoDao;

    @Value("${qmt.http}")
    private String qmtHttp;

    String STOCK_BUY = "23";//证券买入
    String STOCK_SELL = "24";//证券卖出
    String CREDIT_FIN_BUY = "27";//融资买入
    String CREDIT_SLO_SELL = "28";//融券卖出
    String CREDIT_BUY_SECU_REPAY = "29";//买券还券
    String CREDIT_DIRECT_SECU_REPAY = "30";//直接还券
    String CREDIT_SELL_SECU_REPAY = "31";//卖券还款
    String CREDIT_DIRECT_CASH_REPAY = "32";//直接还款

    @Override
    public void sell(String code, int count, String remarks) {
        String order_type = STOCK_SELL;
        HashMap<String, Object> hashMap = new HashMap<>();
        if (CommonUtil.isSh(code)) {
            code += ".SH";
        } else {
            code += ".SZ";
        }
        hashMap.put("code", code);
        hashMap.put("order_type", order_type);
        hashMap.put("count", String.valueOf(count));
        try {
            HttpUtil.get(qmtHttp + "order_stock", hashMap);
            Thread.sleep(2000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            Config.allowRefresh();
        }
    }

    @Override
    public boolean buy(String code, int count, double price, String stockName) {
        if (balance() < (count * price + 2000)) {
            return false;
        }
        if (CommonUtil.isSh(code)) {
            code += ".SH";
        } else {
            code += ".SZ";
        }
        String order_type = CREDIT_FIN_BUY;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code);
        hashMap.put("order_type", order_type);
        hashMap.put("count", String.valueOf(count));
        try {
            String s = HttpUtil.get(qmtHttp + "order_stock", hashMap);
            logger.info("请求返回值:{}", s);
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            Config.allowRefresh();
        }
        return true;
    }


    @Override
    public Double balance() {
        //信用账号可用余额
        String s1 = HttpUtil.get(qmtHttp + "query_credit_detail");
        JSONObject jsonObject = JSONObject.parseObject(s1);
        Double cash2 = jsonObject.getDouble("m_dAvailable");
        Double m_dEnableBailBalance = jsonObject.getDouble("m_dEnableBailBalance");


        //普通账号可用余额
        //String s = HttpUtil.get(qmtHttp + "query_stock_asset");
        //JSONObject jsonObject1 = JSONObject.parseObject(s);
        //Double cash = jsonObject1.getDouble("cash");
        return m_dEnableBailBalance;
    }

    @Override
    public Double positionProfit() {
        String s = HttpUtil.get(qmtHttp + "query_credit_detail");
        JSONObject jsonObject1 = JSONObject.parseObject(s);
        Double positionProfit = jsonObject1.getDouble("m_dPositionProfit");
        return positionProfit;

    }

    public Double sumBalance() {
        String s = HttpUtil.get(qmtHttp + "query_stock_asset");
        JSONObject jsonObject1 = JSONObject.parseObject(s);
        Double m_dAssureAsset = jsonObject1.getDouble("m_dPositionProfit");
        return m_dAssureAsset;
    }

    @Override
    public List<ChiGu> position(int aCount) {
        List<ChiGu> chiGuList = new ArrayList<>();
        String s = HttpUtil.get(qmtHttp + "query_stock_positions");
        JSONArray jsonArray = JSONArray.parseArray(s);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Double open_price = jsonObject.getDouble("open_price");
            if (open_price < 0) {
                //如果成本为负数，直接跳过
                continue;
            }
            Integer volume = jsonObject.getInteger("volume");
            Integer can_use_volume = jsonObject.getInteger("can_use_volume");
            Double market_value = jsonObject.getDouble("market_value");
            String stock_code = jsonObject.getString("stock_code");
            stock_code = stock_code.substring(0, stock_code.indexOf("."));
            NameInfo nameInfo = nameInfoDao.findByCode(stock_code);
            String name = nameInfo == null ? stock_code : nameInfo.getName();
            if (can_use_volume >= aCount) {
                ChiGu chiGu = new ChiGu();
                chiGu.setCode(stock_code);
                chiGu.setName(name);
                chiGu.setCost(open_price);
                chiGu.setSumMoney(market_value);
                chiGu.setYkMoney(0.00);
                chiGu.setYkZf(0.00);
                chiGu.setCount(volume);
                chiGuList.add(chiGu);
            }
        }
        return chiGuList;
    }

    @Override
    public void autoRepayment() {
        String s1 = HttpUtil.get(qmtHttp + "query_credit_detail");
        JSONObject jsonObject = JSONObject.parseObject(s1);
        int m_dAvailable = jsonObject.getInteger("m_dAvailable");
        int m_dTotalDebt = jsonObject.getInteger("m_dTotalDebt");
        if (m_dTotalDebt > 0) {
            int count;
            if (m_dTotalDebt > m_dAvailable) {
                count = m_dAvailable;
            } else {
                count = m_dTotalDebt;
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code", "600000.SH");
            hashMap.put("order_type", CREDIT_DIRECT_CASH_REPAY);
            hashMap.put("count", String.valueOf(count));
            HttpUtil.get(qmtHttp + "order_stock", hashMap);
        }
    }
}
